//
//  FamilyAddViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/24.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

enum FamilyAddType {
    case add
    case edit
    
    var title: String {
        switch self {
        case .add: return "添加成员"
        case .edit: return "家庭成员"
        }
    }
}

/// 与本人关系 2-配偶 3-父母 4-子女 5-其他
enum FamilyRelation: Int {
    case mate = 2
    case parents
    case child
    case other
}

struct FamilyAddModel: HandyJSON {
    var addr: String?
    var city: String?
    var province: String?
    var region: String?
    var consigneeName: String?
    var consigneePhone: String?
    var id: String?
    var isDefault: Int = -1
    
    var relationName: String?
    var phone: String?
    var idcard: String?
    var name: String?
    var relation: String?
    var area: String?
}

class FamilyAddViewModel: NSObject {
    let titles = ["姓名", "身份证号", "地区", "详细地址", "手机号", "与我的关系", "常用就诊人", "确定"]
    let addresses = ["姓名", "手机号", "地区", "详细地址", "设为默认地址", "确定"]
    
    let model: FamilyAddModel
    
    init(model: FamilyAddModel) {
        self.model = model
        self.provinceId = model.province ?? ""
        self.cityId = model.city ?? ""
        self.regionId = model.region ?? ""
        self.area = model.area ?? ""
        self.addr = model.addr ?? ""
        self.id = model.id ?? ""
        self.isDefault = model.isDefault
        
        self.name = model.name ?? ""
        self.phone = model.phone ?? ""
        self.idcard = model.idcard ?? ""
        self.relationName = model.relationName ?? ""
        self.relation = model.relation ?? ""
        
        self.receiveName = model.consigneeName ?? ""
        self.receivePhone = model.consigneePhone ?? ""
    }
    
    var name: String
    var idcard: String
    var phone: String
    var relationName: String
    var relation: String
    
    var provinceId: String
    var cityId: String
    var regionId: String
    var area: String
    var addr: String
    var isDefault: Int
    var id: String
    
    /// 是否删除 0-删除
    var isDelete: Bool = true
    
    var isCommonly: Bool { return isDefault == 1 ? true : false }
    
    var receiveName: String
    var receivePhone: String
    
    var newPhone: String = ""
    
    var reservedPhone: String = ""
    
    var numberOfRows: Int { return titles.count }
    
    var numberOfAddressRows: Int { return addresses.count }
    
    var cellType: FamilyAddFormCellType = .name
    
    var cellHeight: CGFloat {
        switch cellType {
        case .sure: return 110
        default: return 60
        }
    }
    
    var isIdCard: Bool {
        return !idcard.isEmpty && idcard.isValidateIdCard()
    }
    var idCardMsg: String {
        if idcard.isEmpty { return "身份证必填" }
        if !idcard.isValidateIdCard() { return "身份证格式错误" }
        return ""
    }
    
    var isPhone: Bool {
        return !phone.decryptWithAES().isEmpty &&
            phone.decryptWithAES().isPhone()
    }
    var isReceivePhone: Bool {
        return !receivePhone.isEmpty &&
            receivePhone.isPhone()
    }
    var phoneMsg: String {
        if phone.isEmpty { return "手机号必填" }
        if !phone.isPhone() { return "手机号格式错误" }
        return ""
    }
    
    var isName: Bool { return !name.isEmpty }
    var isReceiveName: Bool { return !receiveName.isEmpty }
    var nameMsg: String { return "姓名必填" }
    
    var isArea: Bool { return !provinceId.isEmpty && !cityId.isEmpty && !regionId.isEmpty }
    var areaMsg: String { return "地区必填" }
}

extension FamilyAddViewModel {
    /// 新增或编辑家庭成员
    static func addOrEditFamily(paras: [String: Any],
                                finished: @escaping (_ msg: String?, _ code: HttpCode) -> Void)
    {
        HttpTool.shared.request(target: ApiManager.familyAddOrEdit(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
    
    static func getFamilyMemberDetail(patientId: String,
                                      success: @escaping (_ model: FamilyAddModel) -> Void,
                                      failure: @escaping (_ errorMsg: String?) -> Void)
    {
        let paras = ["id": patientId]
        HttpTool.shared.request(target: ApiManager.familyMemberDetail(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<FamilyAddModel>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 新增或编辑收货地址
    static func addAndEditReceiveAddress(paras: [String: Any],
                                  finished: @escaping (_ msg: String?, _ code: HttpCode) -> Void)
    {
        HttpTool.shared.request(target: ApiManager.addAndEditReceiveAddress(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
    
    /// 获取收货地址详情
    static func getReceiveAddressDetail(addressId: String,
                                        success: @escaping (_ model: FamilyAddModel) -> Void,
                                        failure: @escaping (_ errorMsg: String?) -> Void)
    {
        let paras = ["id": addressId]
        HttpTool.shared.request(target: ApiManager.receiveAddressDetail(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<FamilyAddModel>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    ///删除家庭成员
    static func deleteFamily(familyId: String, finish: @escaping (_ msg: String?, _ code: HttpCode) -> Void) {
        let paras = ["id" : familyId]
        HttpTool.shared.request(target: ApiManager.familyDelete(paras: paras), success: { (json, code) in
            finish(json["msg"].description, code)
        }) { (errorMsg) in
            finish(errorMsg, .failure)
        }
    }
}
